<template>
  <el-dialog
    :close-on-click-modal="false"
    title="选择地址弹窗"
    :visible.sync="show"
    :append-to-body="true"
    width="1200px"
  >
    <div class="mapwrap">
      <!-- 输入框自动完成组件 -->
      <el-autocomplete
        v-model="form.address"
        :maxlength="200"
        :fetch-suggestions="onSearchResult"
        :trigger-on-focus="false"
        placeholder="请搜索或选择地点"
        @select="handleSelect"
        popper-class="dailog-addressbox-list"
        suffix-icon="el-icon-search"
        class="search-box"
        clearable
      >
        <template slot-scope="{ item }">
          <span class="name">{{ item.name }}</span>
          <!-- <span class="addr">{{ item.district }}</span> -->
        </template>
      </el-autocomplete>
      <div :id="mapId" class="amap-mark">
        <!-- <el-amap-marker
          :position="markers.position"
          :events="markers.events"
          :visible="markers.visible"
        >
          <div :style="slotStyle" class="mark-icon">
            <i class="icon-dingwei"></i>
          </div>
        </el-amap-marker>
        <el-amap-info-window
          :position="mwindows.position"
          :visible.sync="mapmarkvisible"
          :events="markevents"
          :content="mwindows.content"
        ></el-amap-info-window> -->
      </div>
    </div>
    <el-row style="margin-top: 15px">
      <el-col :span="20">
        <el-form
          label-width="80px"
          :inline="true"
          ref="form"
          :model="form"
          :rules="rules"
        >
          <el-form-item label="地址" prop="address">
            <el-input v-model="form.address" style="width: 320px" />
          </el-form-item>
          <el-form-item label="经度" prop="lng">
            <el-input v-model="form.lng" />
          </el-form-item>
          <el-form-item label="纬度" prop="lat">
            <el-input v-model="form.lat" />
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="4">
        <el-button type="warning" icon="el-icon-coordinate" @click="startLocate"
          >手动打点定位</el-button
        >
      </el-col>
    </el-row>

    <div slot="footer" class="dialog-footer">
      <el-button @click="closeDialog"> 取消 </el-button>
      <el-button type="primary" @click="handleSave"> 确定 </el-button>
    </div>
  </el-dialog>
</template>

<script>
import AMap from "AMap";
import { validateLng, validateLat } from "@/utils/rulesValidate";

export default {
  name: "MapMark",
  props: {
    visible: {
      required: true,
      default: false,
    },
    gis: {
      type: Object,
      default: null,
    },
    mapId: {
      type: String,
      required: true,
    },
  },
  data() {
    let self = this;
    return {
      map: null,
      mousetool: null,

      slotStyle: {
        color: "#3993F8",
      },
      marker: null,

      // 表单参数
      form: {
        address: "",
        lng: null,
        lat: null,
      },
      // 表单校验
      rules: {
        address: [{ required: true, message: "地址不能为空", trigger: "blur" }],
        lng: [
          { required: true, message: "必填", trigger: "blur" },
          { validator: validateLng, trigger: "blur" },
        ],
        lat: [
          { required: true, message: "必填", trigger: "blur" },
          { validator: validateLat, trigger: "blur" },
        ],
      },
    };
  },
  computed: {
    show: {
      get() {
        return this.visible;
      },
      set(val) {
        this.$emit("update:visible", val);
      },
    },
  },
  methods: {
    closeDialog() {
      //当面板关闭(点击关闭按钮)
      this.show = false;
    },
    handleSave() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          //保存

          this.$emit("getMark", this.form);
          this.show = false;
        }
      });
    },
    onSearchResult(pois, cb) {
      let self = this;
      let searchkey = this.form.address;
      AMap.plugin(["AMap.Autocomplete"], function () {
        var autoOptions = {
          city: "", // 城市，默认全国
        };
        var autoComplete = new AMap.Autocomplete(autoOptions);
        autoComplete.search(searchkey, function (status, result) {
          // 搜索成功时，result即是对应的匹配数据
          if (result && result.tips) {
            let results = result.tips;
            if (results) {
              cb(results);
            } else {
              //搜索无结果
              cb("");
            }
          }
        });
      });
    },
    handleSelect(item) {
      // this.address = item.name + item.district;
      this.form.address = item.name;

      let self = this;
      if (item.location == "") {
        let placemap = new AMap.Geocoder({
          radius: 1000,
          extensions: "all",
        });
        placemap.getLocation(this.form.address, function (status, result) {
          if (status === "complete" && result.info === "OK") {
            self.setSearchPos(result.geocodes[0].location);
          }
        });
      } else {
        self.setSearchPos(item.location);
      }
    },
    setSearchPos(posi) {
      this.map.clearMap();
      this.form.lng = posi.lng;
      this.form.lat = posi.lat;
      this.map.setCenter([posi.lng, posi.lat]);
      this.marker = new AMap.Marker({
        position: [posi.lng, posi.lat],
        map: this.map,
      });

      let infoWindow = new AMap.InfoWindow({
        content: "<span style='color:#999999'>" + this.form.address,
      });

      infoWindow.open(this.map, [posi.lng, posi.lat]);
    },
    firstPlace(pos) {
      this.map.clearMap();
      this.marker = null;
      let self = this;
      let plceposi = [parseFloat(pos.lng), parseFloat(pos.lat)];
      // let placemap = new AMap.Geocoder({
      //   radius: 1000,
      //   extensions: "all"
      // });
      // placemap.getAddress(pos.split(","), function(status, result) {
      //   if (status === "complete" && result.info === "OK") {
      //     if (result && result.regeocode) {
      self.map.setCenter(plceposi);
      if (self.marker) {
        self.marker.setPosition(plceposi);
      } else {
        self.marker = new AMap.Marker({
          position: plceposi,
          map: self.map,
        });
      }

      let infoWindow = new AMap.InfoWindow({
        content: "<span style='color:#999999'>" + self.form.address + "</span>",
      });

      infoWindow.open(self.map, plceposi);
    },
    mapInit() {
      this.map = new AMap.Map(this.mapId, {
        resizeEnable: true,
        zoom: 12,
        zooms: [3, 20],
        expandZoomRange: true,
      });

      // this.map.plugin(["AMap.MapType"], function () {
      //   //地图类型切换
      //   var type = new AMap.MapType({
      //     defaultType: 0, //使用2D地图
      //   });
      //   self.map.addControl(type);
      // });
      // this.map.plugin(["AMap.ToolBar"], function () {
      //   //加载工具条
      //   var tool = new AMap.ToolBar();
      //   self.map.addControl(tool);
      // });
      // this.map.plugin(["AMap.MouseTool"], function () {
      //   //鼠标工具插件
      //   mouseTool = new AMap.MouseTool(self.map);
      // });
      // AMap.event.addListener(mouseTool, "draw", function (event) {
      //   // event.obj 为绘制出来的覆盖物对象
      //   let drawObj = event.obj;

      //   var point = drawObj.getPosition();
      //   self.transportForm.lat = point.lat;
      //   self.transportForm.lng = point.lng;

      //   mouseTool.close(false);
      // });
      // //输入提示
      // var autoOptions = {
      //   input: "transport-tipinput",
      // };
      // var placeSearch = null;
      // var auto = null;
      // this.map.plugin(["AMap.Autocomplete"], function () {
      //   auto = new AMap.Autocomplete(autoOptions);
      // });

      // this.map.plugin(["AMap.PlaceSearch"], function () {
      //   placeSearch = new AMap.PlaceSearch({
      //     map: self.map,
      //   }); //构造地点查询类
      // });

      // AMap.event.addListener(auto, "select", select); //注册监听，当选中某条记录时会触发
      // function select(e) {
      //   placeSearch.setCity(e.poi.adcode);
      //   placeSearch.search(e.poi.name); //关键字查询查询
      // }
    },
    startLocate() {
      this.map.clearMap();
      let self = this;
      if (!this.mousetool) {
        this.map.plugin(["AMap.MouseTool"], function () {
          //鼠标工具插件
          self.mousetool = new AMap.MouseTool(self.map);
          AMap.event.addListener(self.mousetool, "draw", function (e) {
            var drawObj = e.obj;
            var point = drawObj.getPosition();
            self.form.lat = point.lat;
            self.form.lng = point.lng;

            self.mousetool.close(false);
          });
        });
      }

      this.mousetool.marker();
    },
  },
  watch: {
    show: function (val) {
      if (val) {
        if (!this.map) {
          this.$nextTick(function () {
            this.mapInit();
          });
        }
        if (this.gis) {
          this.plugin = [];
          this.$nextTick(function () {
            if (this.gis.address) {
              this.form.address = this.gis.address;
              this.form.lng = this.gis.lng;
              this.form.lat = this.gis.lat;
            }
            this.firstPlace(this.gis);
          });
        } else {
          this.form.address = "";
          this.form.lat = "";
          this.form.lng = "";
          if (this.map) {
            this.map.clearMap();
          }
        }
      }
    },
  },
  mounted() {},
};
</script>

<style lang="scss">
.mapmark {
  .el-dialog__body {
    padding: 0;
  }
}
.mapwrap {
  width: 100%;
  height: calc(100vh - 400px);
  .amap-mark {
    width: 100%;
    height: 100%;
  }
  div {
    &.el-input {
      &:hover {
        span.el-input__suffix {
          .el-icon-search {
            visibility: hidden;
            transition: all 0s;
          }
        }
      }
      input {
        color: #fff;
      }
    }
  }
  .el-input__inner {
    background: rgba(0, 0, 0, 0.7);
  }
  .mark-icon {
    i {
      font-size: 26px !important;
    }
  }
  .search-box {
    width: 300px;
    position: absolute !important;
    margin-left: 50%;
    transform: translateX(-50%);
    margin-top: 10px;
    z-index: 5;
    .el-input__suffix {
      color: #50e3c2;
    }
  }
  .amap-info {
    margin-left: 5px;
    margin-top: -30px;
  }
  .amap-info-close {
    text-decoration: none;
    display: none;
  }
}
</style>
